//
//  WBMainViewController.swift
//  Weibo
//
//  Created by kobe on 2016/12/22.
//  Copyright © 2016年 kobe. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {
    
    // 定时器
    fileprivate var timer:Timer?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupChildControllers()
        setupComposeBtn()
        setupTimer()
        
        setUpNewFeature()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        //销毁定时器
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func userLogin(n:Notification) {
        print("用户登录通知")
        
        var when = DispatchTime.now()
        
        //判断n的object是否有值，如果有值，提示用户重新登录
        if n.object != nil {
            
            SVProgressHUD.setDefaultMaskType(.gradient)

            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            //修改延迟时间
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)

            
            let nav = UINavigationController(rootViewController: WBAuthViewController())
            self.present(nav, animated: true, completion: nil)
            
            
        }
        
        
    }
    
    //使用代码控制设备的方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // 撰写微博
    @objc func composeStatus() {
        
        // FIXME: 判断登录
        
        // 实例化视图
        let view = WBComposeTypeView.composeTypeView()
        
        // 显示视图
        view.show()
    }
    
    //MARK: - 私有控件
    //撰写按钮
    lazy var composebtn:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}

// extension类似于 OC 中的分类 在Swift中还可以用来切分代码块
// 可以把相近功能的函数放在一个extension中 便于代码维护
// 注意:和OC的分类一样 extension中不能定义属性

//MARK: - 设置界面
extension WBMainViewController{
    
    func setupComposeBtn() {
       
        tabBar.addSubview(composebtn)
        
        //设置按钮的位置
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count - 1
        composebtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //按钮监听方法
        composebtn.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    //设置所有子控制器
    func setupChildControllers() {
        
        //获取沙河的json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断data是否有内容，如果没有 说明本地沙河没有文件
        if data == nil {
            
            //从bundle加载data
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = NSData(contentsOfFile: path!)
        }
        
        //data一定会有内容 反序列化
        //从bundle加载配置的json
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]] else {
            return
        }
        
        
        
        /*
        let array = [
            ["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
            
            ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后，别人评论你的微博，发给你的消息，都会在这里收到"]],
            
            ["clsName":"UIViewController"],
            
            ["clsName":"WBDiscoveryViewController","title":"发现","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
            
            ["clsName":"WBProfileViewController",
         "title":"我","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
            
        ]
        
        //测试数据格式是否正确
//        (array as NSArray).write(toFile: "/Users/liwei/Desktop/demo.plist", atomically: true)
        
        //数组转json
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        let fileUrl = NSURL.fileURL(withPath: "/Users/liwei/Desktop/demo.json")
        (data as NSData).write(toFile: "/Users/liwei/Desktop/demo.json", atomically: true)
 */
        
        
        var arrayM = [UIViewController]()
        for dic in array! {
            arrayM.append(controller(dict: dic as [String : AnyObject]))
        }
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
    private func controller(dict:[String:AnyObject]) -> UIViewController{
        // 1.取得字典内容
       guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String:String] else{
            return UIViewController()
        }
        
        // 2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置控制器的访客信息字典
        vc.visitorInforDictionary = visitorDict
        
        //设置tabbar的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.black], for: .highlighted)
//  修改标题大小
//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 24)], for: UIControlState(rawValue:0))
        
        //实例化导航栏控制器的时候会调用push方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
        

        
    }
}

// MARK: - 定时器
extension WBMainViewController {
    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    //定时器触发方法
    @objc fileprivate func updateTimer() {
        
        if !WBNetworkManager.shared.userLogin {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (unreadCount) in
             //设置tabbarItem的badgeNumber
            self.tabBar.items?[0].badgeValue = unreadCount > 0 ? "\(unreadCount)" : nil
            
            //设置图标的 badgeNumber
//            UIApplication.shared.applicationIconBadgeNumber = unreadCount
            
        }
    }
}


// MARK: - uitabbarcontroller 代理方法
extension WBMainViewController:UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        
        // 获取控制器在数组中的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        //判断当前索引是首页 同事index也是首页 重复点击首页的按钮
        if selectedIndex == 0 && index == selectedIndex{
            print("首页")
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0, y:-64), animated: true)
            
            //刷新数据 增加延迟 保证表格先滚动到顶部再刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
            // 清楚badgeNumber
            vc.tabBarItem.badgeValue = nil
            
            
        }
        
        
        //判断目标控制器是否是 UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
}

extension WBMainViewController {
    
    fileprivate func setUpNewFeature() {
    
        //判断是否登录
        if !WBNetworkManager.shared.userLogin {
            return
        }
        
        
        //更新:显示新特性 没更新:欢迎
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        view.addSubview(v)
        
        
    }
    
    private var isNewVersion:Bool {
        
        //去当前的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        
        //保存在document目录中的之前的版本号
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        let sanboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print(path)
        
        //将当前版本号保存在沙盒
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //比较版本号
        return currentVersion != sanboxVersion
    }
}







